package com.codingman.thymeleafdemo2;

import javax.servlet.ServletContext;

import org.thymeleaf.TemplateEngine;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;

public class ThymeleafUtil {
	private TemplateEngine engine;

	private static ThymeleafUtil instance;

	private ThymeleafUtil(ServletContext context) {
		ServletContextTemplateResolver resolver = new ServletContextTemplateResolver(context);

		String prefix = context.getInitParameter("thymeleaf.prefix");
		String suffix = context.getInitParameter("thymeleaf.suffix");
		String mode = context.getInitParameter("thymeleaf.mode");
		String encoding = context.getInitParameter("thymeleaf.encoding");
		String cacheable = context.getInitParameter("thymeleaf.cacheable");

		resolver.setTemplateMode(mode);
		resolver.setPrefix(prefix);
		resolver.setSuffix(suffix);
		resolver.setCharacterEncoding(encoding);
		resolver.setCacheable(Boolean.valueOf(cacheable));
		
		this.engine = new TemplateEngine();
		this.engine.setTemplateResolver(resolver);
	}
	
	public static ThymeleafUtil getInstance(ServletContext context){
        if (instance == null){
        	instance = new ThymeleafUtil(context);
        }
        return instance;
    }
	
	public static TemplateEngine getTemplateEngine(ServletContext context){
        return getInstance(context).getTemplateEngine();
    }
	
	public TemplateEngine getTemplateEngine(){
        return this.engine;
    }
}
